package com.terrace.core.spring.servlet.handler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.terrace.core.common.model.ResultData;
import com.terrace.core.utils.JsonUtils;

/**
 * 平台的统一异常处理
 * @author jiangyg
 *
 */
public class PlatformMappingExceptionResolver extends SimpleMappingExceptionResolver {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(PlatformMappingExceptionResolver.class);
	
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex) {
		String viewName = determineViewName(ex, request);
		if (StringUtils.isNotBlank(viewName)) {
			if (!(request.getHeader("accept").indexOf("application/json") > -1
					|| (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				return getModelAndView(viewName, ex, request);
			} else {
				// Ajax返回
				try {
					response.setCharacterEncoding("UTF-8");
					response.setContentType("application/json;charset=UTF-8");
					PrintWriter writer = response.getWriter();
					ResultData result = new ResultData();
					result.setStatus("15000");
					logger.error("后台出错信息：", ex);
					writer.println(JsonUtils.beanToJson(result));
					writer.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}
		}
		return null;
	}

}